﻿
(function (doc, win) {
    var docEl = doc.documentElement,
      resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
      recalc = function () {
          var clientWidth = docEl.clientWidth;
          if (!clientWidth) return;
          docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
      };

    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);


function GetPre(str) {
    if (!str) return '';
    var pos = str.lastIndexOf("/");
    if (pos >= 0) str = str.substr(0, pos) + "/pre" + str.substr(pos);
    return str;
}
var moreTmpl = '<div class="last  showMore"><div class="data"></div><div class="more">点击显示更多</div><div class="clearfix"></div></div>';
var noneTmpl = '<div class="last "><div class="data"></div><div class="noMore"><ul><li>没有更多了</li></ul></div><div class="clearfix"></div></div>';
var showMoreTmpl = '<div class="common-fullButton showMore"><ul><li>显示更多</li></ul></div>';
var nodataTmpl = '<div class="centerPrompt marginTop"><div class="pic"><img src="/media/wechat/img/logoGrey.png" /></div><div class="massage greyFont">抱歉，没有找到任何结果</div></div>';
var loadingTmpl = "&nbsp;<img src='/media/images/nowloading.gif' style='height:0.8rem' />&nbsp;正在加载，请稍后……";

function Nodata(pager) {
    pager.empty();
    $(nodataTmpl).appendTo(pager);
}


$.fn.modal = $.fn.myModal;
$.views.converters({ ToPre: GetPre });

jQuery.fn.extend({
    LoadMore: function (set) {
        set = jQuery.extend({
            noData: "暂无数据",
            queryed: null, //查询完成后的回调
            pageSize: 10,//每页行数   
            Type: 1,
            handleName: null,//handle  
            tmpl: "#listTmpl",
            events: [],//事件集合
            getPostKey: function () { return {}; }//获取提交数据的方法 
        }, set);

        var result = {
            pager: $("#pager"),
            $list: $(this),
            currentData: null,
            currentIndex: 1,
            settings: set,
            Query: function (pageIndex) {
                result.pager.html(loadingTmpl);
                if (pageIndex) result.currentIndex = pageIndex;
                pageIndex = result.currentIndex;
                if (pageIndex === 1) result.$list.html("");

                var settings = result.settings;
                var postData = settings.getPostKey();
                postData["pageSize"] = settings.pageSize;
                postData["pageIndex"] = pageIndex;
                var url = settings.handleName;
                if (typeof (url) == "function") url = url();
                $.ajax({
                    url: url,
                    data: postData,
                    success: function (data) {

                        if (data.Data == null || data.Data.Count === 0) {
                            Nodata(result.pager);
                            return;
                        }
                        var tmpl = null;
                        if (typeof (set.tmpl) == "function") {
                            tmpl = $.Loadtmpl(set.tmpl());
                        } else {
                            tmpl = $.Loadtmpl(set.tmpl);
                        }
                        result.$list.append(tmpl.render(data.Data.Data));

                        if (result.settings.queryed) {
                            result.settings.queryed(data.Data);
                        }
                        var pageCount = data.Data.PageInfo.PageCount;
                        settings.Type === 1 ? result.pager.html(pageCount > result.currentIndex ? moreTmpl : noneTmpl) : result.pager.html(pageCount > result.currentIndex ? showMoreTmpl : "");
                    }
                });
                return result;
            }
        };
        result.pager.on("click", ".showMore", function () {
            result.Query(result.currentIndex + 1);
        });
        return result;
    },

    BindList: function (listTmpl, data, msgtext, noTmpl) {  //绑定列表并在没数据的时候显示暂无数据
        $(this).parent().find(".noResult").remove();
        if (!noTmpl) noTmpl = "NoResult";
        $(this).Link(listTmpl, data);

        if (!data || data.length == 0) {

            var noresult = $("<div class='noResult'></div>");
            console.log(noTmpl);
            noresult.Render(noTmpl);

            if (msgtext) noresult.find(".massage").text(msgtext);
            noresult.insertAfter(this);
        }
    },
});

///跳转到微信端首页
function goToWxIndex() {
    window.location.href = '/wechat/index.aspx';
}


//跳转到注册页面
function needRegister(uid) {
    if (!Param.IsRegister) {
        $.cookie("lasturl", window.location.href, { path: '/' });
        window.location.href = "/wechat/register.aspx?" + $.param({ uid: uid });
    }
}

//跳转到最后访问的页面或者首页
function goToLastUrl() {
    var lasturl = $.cookie("lasturl");
    console.log(lasturl);
    if (!lasturl || lasturl == undefined) goToWxIndex();
    $.removeCookie("lasturl");
    window.location.href = lasturl;
}

function scanCode(act) {


    wx.error(function (res) {
        alert("微信初始化错误，请重新打开页面")
    });
    wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {

            var cardCode = "";
            if (res.resultStr.indexOf(",") > 0) {
                cardCode = res.resultStr.split(",")[1];
            } else {
                cardCode = res.resultStr;
            }
            act(cardCode);
        }
    });
}

function getExcel(table, name) {
    var uri = 'data:application/vnd.ms-excel;base64,'
      , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
      , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
      , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
    if (!table.nodeType) table = $(table);// document.getElementById(table)
    var obj = table.html();

    var ctx = { worksheet: 'Worksheet', table: obj }
    return uri + base64(format(template, ctx));
}

var tableToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,'
      , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
      , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
      , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
    return function (table, name) {
        if (!table.nodeType) table = $(table);// document.getElementById(table)
        var obj = table.html();


        var ctx = { worksheet: name || 'Worksheet', table: obj }

        window.location.href = uri + base64(format(template, ctx))
    }
})()


function GetType(isTickets) {
    $.get("/api/ProductType/getlist", function (result) {
        if (result.IsSuccess) {
            var data = [{ DictId: "", Name: "全部类型" }]
            $.each(result.Data, function (i, o) {
                data.push(o)
                if (o.IsTicket && isTickets) {
                    $("#ProductType").html(o.Name);
                }
            });
            $("#ProductTypeList").Link("ProductTypeList", data);
        }
    })
}

function InitGallery(type) {
    $.get("/api/Gallery/GetGalleryList", { type: type }, function (result) {
        if (result.IsSuccess) {
            var data = { Images: result.Data };
            console.log(data);
            $(".addWrap").Render("#GalleryImageTmpl", data);
            var second = 5000;
            if (type != 2) {
                second = window.Param.ScrollSecond;
                if (second <= 0) second = 5000;
            }
            var bullets = $("#position").find("li");
            $("#position").data("index", 0);
            var banner = Swipe($('#mySwipe')[0], {
                auto: second,
                continuous: true,
                disableScroll: false,
                callback: function (pos) {
                    var i = bullets.length;
                    $(document).resize();
                    if (pos > i) pos = parseInt(pos / 2);
                    bullets.removeClass("cur");
                    bullets.eq(pos).addClass('cur');
                }
            });

        }
    })
}

$.fn.InputTable = function (set) {
    var $this = $(this);
    var setting = $.extend({}, set);
    $this.on("click", ".btnAddRow", function () {
        var $tr = $($.templates(setting.tmpl).render(setting.defaultObject));
        $this.find("tbody").append($tr);
        $tr.initForm();
        $this.trigger("after.AddRow", $tr);
    }).on("click", ".btnRemove", function () {
        if (!confirm("是否要删除此行数据"))
            return false;
        $(this).closest("tr").remove();
        return true;
    });
    return $this;
};


$.fn.InputTableInsert = function (set) {
    var $this = $(this);
    var setting = $.extend({}, set);
    var $tr = $($.templates(setting.tmpl).render(setting.defaultObject));
    $this.find("tbody").append($tr);
    $tr.initForm();
    $this.trigger("after.AddRow", [$tr, setting.defaultObject]);
    return $this;
};
jQuery.fn.extend({
    scrollEnd: function (item, act) {
        var $this = $(this);
        $(".main").on("scroll", function () {
            var scrollTop = $this.scrollTop();
            var scrollHeight = $(item).height();
            var windowHeight = $this.height();
            if (scrollTop + windowHeight >= scrollHeight - 50) {
                act();
            }
        });
    }
});

$(function () {
    $.views.converters({
        ToTime: function (value) {
            //console.log(value);
            return value ? DateTime.Parse(value).format("hh:mm:ss") : "";
        },
        ToYearWeekDate: function (value) {
        
            return value ? DateTime.Parse(value).format("yyyy:MM:dd ") : "";
        },
        ToDateTi: function (value) {
            return value ? DateTime.Parse(value).format("MM月dd日") : "";
        },
        ToWeekday: function (value) {
            return value ? DateTime.Parse(value).format("MMdd-ddd").substr(5) : "";
        },
        ToFixed: function (str) {
            return ToFixed(str, 2); // str.toFixed(2);
        }
    })
})
function ToFixed(obj, length) {
    if (!length) length = 2;
    return isInteger(obj) ? obj : obj.toFixed(length);
}
function isInteger(obj) {
    return Math.floor(obj) === obj;
}
//.main 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
$(function () {
    if (!$('input#test')) {
        if (/Android/gi.test(navigator.userAgent)) {
            function change() {
                if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                    $(".main").scrollTop($(document.activeElement).offset().top);
                }
            }
            window.addEventListener("resize", function () { change(); });

            $("body").on("focus", "input,textarea", function () {
                change();
            });

        }

        $(".service-phone").insertAfter(".footNav");
    }
});
